package com.mai4j.maiadmin.validation.constraintvalidators;

import com.jfinal.kit.StrKit;
import com.mai4j.maiadmin.validation.constraints.LanguageTag;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * Created by 席有芳 on 2021/12/18.
 *
 * @author 席有芳
 */
public class LanguageTagValidator implements ConstraintValidator<LanguageTag, String> {

    private static List<String> languageTags = null;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrKit.isBlank(value)) {
            return true;
        }
        return getAvailableLanguageTags().contains(value);
    }

    /**
     * 获取有效的Locales
     *
     * @return availableLocales
     */
    static synchronized List<String> getAvailableLanguageTags() {
        if (languageTags == null) {
            languageTags = Arrays.stream(Locale.getAvailableLocales())
                    .map(Locale::toLanguageTag)
                    .filter(StrKit::notBlank)
                    .collect(Collectors.toList());
        }
        return languageTags;
    }
}
